const api = require('../../utils/api.js');
import { getPersonaAvatar, getPersonaName, getUserAvatarUrl, getDefaultUserAvatar } from '../../utils/persona.js';

Page({
  data: {
    roles: [
      '司绪', '安心', '小阳', '明心爷爷', '星语', '理理', '笑笑', '林深', '远航', '喵喵', '星云', '东坡先生', '武则天', '迅哥儿', '伍尔芙女士', '老马克'
    ],
    roleKeys: [
      'professional', 'therapist', 'youthful', 'wise_elder', 'artistic', 'tech_rational', 'humorous', 'nature_healer', 'life_coach', 'animal_companion', 'spiritual_guide', 'su_shi', 'wu_ze_tian', 'lu_xun', 'woolfe', 'mark_twain'
    ],

    roleIndex: 0,
    messages: [],
    inputValue: '',
    conversationId: '',
    scrollTop: 0,
    scrollIntoView: '',
    loading: false,
    userAvatar: '',
    isExistingConversation: false,
    topic: '',
    currentPersona: {
      key: '',
      name: '',
      avatar: ''
    },
    isRecording: false,
    recorderManager: null,
    innerAudioContext: null,
    currentPlayingAudio: null,
    currentPlayingIndex: null,
    selectedImage: '',
    previewImageUrl: '',
    debugInfo: '',
    isAudioPlaying: false,
    showEmojiPanel: false,
    emojiList: [
      '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣',
      '😊', '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰',
      '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜',
      '🤪', '🤨', '🧐', '🤓', '😎', '🤩', '🥳', '😏',
      '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣',
      '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠',
      '😡', '🤬', '🤯', '😳', '🥵', '🥶', '😱', '😨',
      '😰', '😥', '😓', '🤗', '🤔', '🤭', '🤫', '🤥',
      '😶', '😐', '😑', '😯', '😦', '😧', '😮', '😲',
      '🥱', '😴', '🤤', '😪', '😵', '🤐', '🥴', '🤢',
      '🤮', '🤧', '😷', '🤒', '🤕', '🤑', '🤠', '💩',
      '👻', '💀', '☠️', '👽', '👾', '🤖', '😺', '😸'
    ]
  },

  onLoad(options) {
    this.initAudioContexts();
    this.loadPage(options);
  },

  onUnload() {
    if (this.data.innerAudioContext) {
      this.data.innerAudioContext.destroy();
    }
    if (this.data.currentPlayingAudio) {
      this.data.currentPlayingAudio.stop();
    }
    // 确保停止波浪动画
    this.setData({ 
      currentPlayingAudio: null, 
      currentPlayingIndex: null,
      isAudioPlaying: false
    });
  },

  initAudioContexts() {
    console.log('开始初始化录音管理器...');
    const recorderManager = wx.getRecorderManager();

    recorderManager.onStart(() => {
      console.log('录音开始 - onStart 被调用');
      this.setData({ isRecording: true, debugInfo: '录音已开始' });
    });

    recorderManager.onStop((res) => {
      console.log('录音结束 - onStop 被调用:', res);
      this.setData({ isRecording: false, debugInfo: '录音已结束，处理中...' });
      this.handleVoiceInput(res);
    });

    recorderManager.onError((res) => {
      console.error('录音错误 - onError 被调用:', res);
      this.setData({ isRecording: false, debugInfo: '录音失败' });
      wx.showToast({ title: '录音失败', icon: 'none' });
    });

    const innerAudioContext = wx.createInnerAudioContext();
    innerAudioContext.onEnded(() => {
      this.setData({ 
        currentPlayingAudio: null, 
        currentPlayingIndex: null,
        isAudioPlaying: false
      });
    });
    innerAudioContext.onError((res) => {
      wx.showToast({ title: '音频播放失败', icon: 'none' });
      this.setData({ 
        currentPlayingAudio: null, 
        currentPlayingIndex: null,
        isAudioPlaying: false
      });
    });

    this.setData({
      recorderManager,
      innerAudioContext
    });

    console.log('录音管理器初始化完成');
  },

  onStartVoice() {
    console.log('=== 录音按钮被点击 ===');
    console.log('当前录音状态:', this.data.isRecording);
    console.log('recorderManager:', this.data.recorderManager);

    this.setData({ debugInfo: `录音按钮点击，当前状态: ${this.data.isRecording}` });

    if (this.data.isRecording) {
      console.log('准备停止录音...');
      this.stopVoice();
    } else {
      console.log('准备开始录音...');
      this.startVoice();
    }
  },

  startVoice() {
    const { recorderManager } = this.data;
    console.log('调用 startVoice，recorderManager:', recorderManager);

    if (!recorderManager) {
      console.error('recorderManager 未初始化！');
      this.setData({ debugInfo: 'recorderManager 未初始化！' });
      wx.showToast({ title: '录音管理器未初始化', icon: 'none' });
      return;
    }

    wx.getSetting({
      success: (res) => {
        console.log('录音权限检查结果:', res.authSetting);
        if (res.authSetting['scope.record'] === false) {
          this.setData({ debugInfo: '录音权限被拒绝' });
          wx.showModal({
            title: '需要录音权限',
            content: '请在设置中开启录音权限',
            success: (modalRes) => {
              if (modalRes.confirm) {
                wx.openSetting();
              }
            }
          });
          return;
        }

        this.setData({ debugInfo: '开始录音...' });
        recorderManager.start({
          duration: 60000,
          sampleRate: 16000,
          numberOfChannels: 1,
          encodeBitRate: 48000,
          format: 'mp3'
        });
      }
    });
  },

  stopVoice() {
    const { recorderManager } = this.data;
    console.log('调用 stopVoice，recorderManager:', recorderManager);

    if (!recorderManager) {
      console.error('recorderManager 未初始化！');
      this.setData({ debugInfo: 'recorderManager 未初始化！' });
      wx.showToast({ title: '录音管理器未初始化', icon: 'none' });
      return;
    }

    this.setData({ debugInfo: '停止录音...' });
    recorderManager.stop();
  },

  async handleVoiceInput(res) {
    console.log('录音结束，开始处理语音输入:', res);
    const { tempFilePath, duration } = res;

    if (!tempFilePath) {
      console.error('录音文件路径为空');
      this.setData({ debugInfo: '录音文件为空' });
      wx.showToast({ title: '录音文件为空', icon: 'none' });
      return;
    }

    try {
      this.setData({ debugInfo: '开始转换录音文件为base64...' });
      const fileBase64 = await this.fileToBase64(tempFilePath);
      this.setData({ debugInfo: '录音文件转换成功，开始发送...' });

      // 计算音频时长
      const audioDuration = this.formatDuration(duration);
      
      await this.sendMessage(null, null, fileBase64, audioDuration);
      this.setData({ debugInfo: '语音消息发送成功' });
    } catch (error) {
      console.error('处理语音输入失败:', error);
      this.setData({ debugInfo: '语音处理失败' });
      wx.showToast({ title: '语音处理失败', icon: 'none' });
    }
  },

  async loadPage(options) {
    const token = api.getAccessToken();
    if (!token) {
      wx.showModal({
        title: '提示',
        content: '请先登录',
        showCancel: false,
        success: () => {
          wx.redirectTo({ url: '/pages/login/login' });
        }
      });
      return;
    }

    await this.fetchUserAvatar();
    
    // 初始化当前人设
    const defaultPersonaKey = this.data.roleKeys[this.data.roleIndex];
    const defaultPersonaAvatar = getPersonaAvatar(defaultPersonaKey);
    const defaultPersonaName = getPersonaName(defaultPersonaKey);
    
    this.setData({
      currentPersona: {
        key: defaultPersonaKey,
        name: defaultPersonaName,
        avatar: defaultPersonaAvatar
      }
    });
    
    if (options.persona) {
      const personaIndex = this.data.roleKeys.indexOf(options.persona);
      if (personaIndex !== -1) {
        const personaAvatar = getPersonaAvatar(options.persona);
        const personaName = getPersonaName(options.persona);
        this.setData({ 
          roleIndex: personaIndex,
          currentPersona: {
            key: options.persona,
            name: personaName,
            avatar: personaAvatar
          }
        });
      }
    }
    
    if (options.conversationId) {
      this.setData({
        conversationId: options.conversationId,
        topic: decodeURIComponent(options.topic || ''),
        isExistingConversation: true
      });
      await this.loadExistingConversation();
    } else {
      await this.startNewConversation();
    }
  },

  async fetchUserAvatar() {
    try {
      const res = await api.getUserInfo();
      let avatarUrl = getUserAvatarUrl(res.data.avatar_url);
      this.setData({ userAvatar: avatarUrl });
    } catch (e) {
      console.error('获取用户头像失败:', e);
      this.setData({ userAvatar: getDefaultUserAvatar() });
    }
  },

  getCurrentPersonaAvatar() {
    if (this.data.currentPersona && this.data.currentPersona.avatar) {
      return this.data.currentPersona.avatar;
    }
    const personaKey = this.data.roleKeys[this.data.roleIndex];
    return getPersonaAvatar(personaKey);
  },

  getCurrentPersonaName() {
    if (this.data.currentPersona && this.data.currentPersona.name) {
      return this.data.currentPersona.name;
    }
    const personaKey = this.data.roleKeys[this.data.roleIndex];
    return getPersonaName(personaKey);
  },

  async loadExistingConversation() {
    try {
      this.setData({ loading: true });
      const response = await api.getConversationDetail(this.data.conversationId);
      
      if (response.code === 200 && response.data) {
        const messages = response.data.messages || [];
        const currentPersonaAvatar = this.getCurrentPersonaAvatar();
        const processedMessages = messages.map(record => ({
          from: record.role === 'user' ? 'user' : 'ai',
          text: record.content,
          avatar: record.role === 'user' ? this.data.userAvatar : currentPersonaAvatar,
          messageId: record.message_id,
          createdAt: record.created_at,
          audioBase64: record.audio_base64 || null,
          imageBase64: record.image_base64 || null
        }));

        this.setData({
          messages: processedMessages,
          loading: false
        });
        this.scrollToBottom();
      } else {
        wx.showToast({ title: '加载对话失败', icon: 'none' });
        this.setData({ loading: false });
      }
    } catch (error) {
      console.error('加载对话失败:', error);
      wx.showToast({ title: '加载对话失败', icon: 'none' });
      this.setData({ loading: false });
    }
  },

  async startNewConversation() {
    try {
      const currentPersona = this.data.roleKeys[this.data.roleIndex];
      console.log('启动新会话，当前人设:', currentPersona);
      console.log('roleKeys:', this.data.roleKeys);
      console.log('roleIndex:', this.data.roleIndex);
      
      const response = await api.startConversation(currentPersona);
      console.log('启动会话API响应:', response);
      
      if (response.status === 'success') {
        const currentPersonaAvatar = this.getCurrentPersonaAvatar();
        const currentPersonaName = this.getCurrentPersonaName();
        console.log('设置会话数据，头像:', currentPersonaAvatar, '名称:', currentPersonaName);
        console.log('初始消息:', response.initial_message);
        
        this.setData({
          conversationId: response.conversation_id,
          messages: [{
            from: 'ai',
            text: response.initial_message.message || `你好，我是${currentPersonaName}，有什么想聊的吗？`,
            avatar: currentPersonaAvatar,
            audioBase64: response.initial_message.audio_base64 || null
          }]
        });
        
        // 如果有音频，自动播放
        if (response.initial_message.audio_base64) {
          console.log('检测到音频，准备自动播放');
          setTimeout(() => {
            this.onPlayAudio({ currentTarget: { dataset: { audio: response.initial_message.audio_base64, index: 0 } } });
          }, 500);
        } else {
          console.log('没有检测到音频');
        }
      } else {
        console.error('启动会话失败:', response);
        wx.showToast({ title: response.message || '启动会话失败', icon: 'none' });
      }
    } catch (error) {
      console.error('启动会话失败:', error);
      wx.showToast({ title: '启动会话失败', icon: 'none' });
    }
  },

  goBack() {
    wx.navigateBack();
  },

  async onRoleChange(e) {
    if (this.data.isExistingConversation) {
      wx.showToast({ title: '现有对话不能切换人设', icon: 'none' });
      return;
    }

    const newIndex = e.detail.value;
    const newPersona = this.data.roleKeys[newIndex];
    const newPersonaAvatar = getPersonaAvatar(newPersona);
    const newPersonaName = getPersonaName(newPersona);
    
    // 先保存当前的conversationId
    const currentConversationId = this.data.conversationId;
    
    this.setData({
      roleIndex: newIndex,
      currentPersona: {
        key: newPersona,
        name: newPersonaName,
        avatar: newPersonaAvatar
      },
      messages: [],
      conversationId: ''
    });

    // 如果有现有对话，尝试切换人设
    if (currentConversationId) {
      try {
        await api.switchPersona(currentConversationId, newPersona);
      } catch (error) {
        console.log('切换人设失败，将创建新对话:', error);
      }
    }

    await this.startNewConversation();
  },

  onInput(e) {
    this.setData({ inputValue: e.detail.value });
  },

  async onSendMsg() {
    const { inputValue, selectedImage, loading, conversationId } = this.data;
    if (loading) return;
    
    // 检查是否有消息内容（文本或图片）
    const hasText = inputValue && inputValue.trim();
    const hasImage = selectedImage;
    
    if (!hasText && !hasImage) {
      wx.showToast({ title: '请输入消息或选择图片', icon: 'none' });
      return;
    }
    
    if (!conversationId) {
      wx.showToast({ title: '会话未初始化，请重新进入', icon: 'none' });
      return;
    }
    
    // 立即设置loading状态，防止重复发送
    this.setData({ loading: true });
    
    try {
      // 处理图片数据：保持完整的data URL格式
      let processedImage = null;
      if (selectedImage) {
        if (selectedImage.startsWith('data:image/')) {
          // 保持完整的data URL格式
          processedImage = selectedImage;
        } else {
          // 如果不是data URL格式，添加前缀
          processedImage = `data:image/jpeg;base64,${selectedImage}`;
        }
      }
      
      await this.sendMessage(inputValue, processedImage, null);
      this.setData({ inputValue: '', selectedImage: '' });
    } catch (error) {
      console.error('发送消息失败:', error);
      // 发送失败时重置loading状态
      this.setData({ loading: false });
    }
  },

  async sendMessage(text, imageBase64 = null, audioBase64 = null, audioDuration = null) {
    const { messages, conversationId, userAvatar } = this.data;
    
    // 确保有消息内容
    const messageText = text || (imageBase64 ? '图片消息' : audioBase64 ? '语音消息' : '');
    if (!messageText && !imageBase64 && !audioBase64) {
      console.error('消息内容为空');
      return;
    }
    
    const userMessage = {
      from: 'user',
      text: messageText,
      avatar: userAvatar || getDefaultUserAvatar(),
      imageBase64: imageBase64,
      audioBase64: audioBase64,
      audioDuration: audioDuration
    };

    messages.push(userMessage);

    this.setData({
      messages,
      inputValue: ''
      // 注意：loading状态已经在onSendMsg中设置，这里不再重复设置
    });

    this.scrollToBottom();

    try {
      const response = await api.sendMessage(conversationId, messageText, imageBase64, audioBase64);
      if (response.status === 'success') {
        const currentPersonaAvatar = this.getCurrentPersonaAvatar();
        messages.push({
          from: 'ai',
          text: response.response,
          avatar: currentPersonaAvatar,
          audioBase64: response.audio_base64 || null
        });
        if (response.audio_base64) {
          setTimeout(() => {
            this.onPlayAudio({ currentTarget: { dataset: { audio: response.audio_base64, index: messages.length - 1 } } });
          }, 500);
        }
      } else {
        const currentPersonaAvatar = this.getCurrentPersonaAvatar();
        messages.push({
          from: 'ai',
          text: response.message || '抱歉，我现在无法回复，请稍后再试。',
          avatar: currentPersonaAvatar
        });
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      const currentPersonaAvatar = this.getCurrentPersonaAvatar();
      messages.push({
        from: 'ai',
        text: '网络连接失败，请检查网络后重试。',
        avatar: currentPersonaAvatar
      });
    }

    this.setData({
      messages,
      loading: false
    });

    this.scrollToBottom();
  },

  // 播放/暂停音频
  onPlayAudio(e) {
    const audioBase64 = e.currentTarget.dataset.audio;
    const messageIndex = parseInt(e.currentTarget.dataset.index);
    const { innerAudioContext, currentPlayingAudio, currentPlayingIndex } = this.data;
    
    console.log('播放音频 - messageIndex:', messageIndex, 'type:', typeof messageIndex, 'currentPlayingIndex:', currentPlayingIndex, 'type:', typeof currentPlayingIndex, 'isAudioPlaying:', this.data.isAudioPlaying);
    
    if (!audioBase64) {
      wx.showToast({ title: '没有音频内容', icon: 'none' });
      return;
    }
    
    // 如果点击的是当前正在播放的音频，则停止播放
    if (currentPlayingIndex === messageIndex && currentPlayingAudio) {
      console.log('停止当前播放的音频');
      this.stopAudio();
      return;
    }
    
    // 如果当前有音频在播放，先停止
    if (currentPlayingAudio) {
      currentPlayingAudio.stop();
    }
    
    // 确保音频数据格式正确
    let audioSrc = audioBase64;
    if (!audioBase64.startsWith('data:audio/')) {
      audioSrc = `data:audio/mp3;base64,${audioBase64}`;
    }
    
    // 设置音频源并播放
    innerAudioContext.src = audioSrc;
    innerAudioContext.play();
    
    console.log('开始播放音频，设置状态');
    this.setData({ 
      currentPlayingAudio: innerAudioContext,
      currentPlayingIndex: messageIndex,
      isAudioPlaying: true
    });
  },

  stopAudio() {
    const { currentPlayingAudio } = this.data;
    console.log('停止音频 - currentPlayingAudio:', currentPlayingAudio);
    if (currentPlayingAudio) {
      currentPlayingAudio.stop();
      console.log('设置音频停止状态');
      this.setData({ 
        currentPlayingAudio: null,
        currentPlayingIndex: null,
        isAudioPlaying: false
      });
    }
  },

  // 图片输入相关
  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        const imageBase64 = await this.fileToBase64(tempFilePath);
        const fileType = tempFilePath.toLowerCase().includes('.png') ? 'png' : 'jpeg';
        const fullImageBase64 = `data:image/${fileType};base64,${imageBase64}`;
        this.setData({ selectedImage: fullImageBase64 });
      }
    });
  },

  removeSelectedImage() {
    this.setData({ selectedImage: '' });
  },

  fileToBase64(filePath) {
    return new Promise((resolve, reject) => {
      wx.getFileSystemManager().readFile({
        filePath: filePath,
        encoding: 'base64',
        success: (res) => resolve(res.data),
        fail: reject
      });
    });
  },

  // 图片预览功能
  previewImage(e) {
    const src = e.currentTarget.dataset.src;
    this.setData({ previewImageUrl: src });
  },

  closePreviewImage() {
    this.setData({ previewImageUrl: '' });
  },

  async recordEmotion() {
    try {
      wx.showLoading({ title: '正在记录...', mask: true });
      const { messages, conversationId } = this.data;
      const recentMessages = messages.slice(-10);
      const emotionContent = recentMessages.map(msg => 
        `${msg.from === 'user' ? '用户' : 'AI'}: ${msg.text}`
      ).join('\n');

      const response = await api.recordEmotionFromConversation({
        conversation_id: conversationId,
        content: emotionContent
      });

      wx.hideLoading();

      if (response.status === 'success') {
        wx.showModal({
          title: '记录成功',
          content: response.ai_response || '对话情绪已记录到情绪列表中',
          showCancel: false,
          confirmText: '确定',
          success: () => {
            wx.showActionSheet({
              itemList: ['继续对话', '返回主页'],
              success: (res) => {
                if (res.tapIndex === 1) {
                  wx.switchTab({ url: '/pages/index/index' });
                }
              }
            });
          }
        });
      } else {
        wx.showToast({ title: response.message || '记录失败', icon: 'none' });
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({ title: '记录失败', icon: 'none' });
    }
  },

  showMoreOptions() {
    wx.showActionSheet({
      itemList: ['清空对话', '导出对话', '设置'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0: this.clearConversation(); break;
          case 1: this.exportConversation(); break;
          case 2: this.showSettings(); break;
        }
      }
    });
  },

  clearConversation() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空当前对话吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ messages: [] });
          wx.showToast({ title: '对话已清空', icon: 'success' });
        }
      }
    });
  },

  exportConversation() {
    const { messages } = this.data;
    const exportText = messages.map(msg => 
      `${msg.from === 'user' ? '用户' : 'AI'}: ${msg.text}`
    ).join('\n\n');

    wx.setClipboardData({
      data: exportText,
      success: () => {
        wx.showToast({ title: '对话已复制到剪贴板', icon: 'success' });
      }
    });
  },

  showSettings() {
    wx.showToast({ title: '设置功能开发中', icon: 'none' });
  },

  scrollToBottom() {
    setTimeout(() => {
      this.setData({ scrollTop: 999999 });
    }, 100);
  },

  // 格式化音频时长
  formatDuration(duration) {
    if (!duration) return '0:00';
    const minutes = Math.floor(duration / 1000 / 60);
    const seconds = Math.floor((duration / 1000) % 60);
    return `${minutes}:${seconds.toString().padStart(2, '0')}`;
  },

  // 表情包相关功能
  toggleEmojiPanel() {
    this.setData({
      showEmojiPanel: !this.data.showEmojiPanel
    });
  },

  closeEmojiPanel() {
    this.setData({
      showEmojiPanel: false
    });
  },

  selectEmoji(e) {
    const emoji = e.currentTarget.dataset.emoji;
    const { inputValue } = this.data;
    
    // 将表情添加到输入框
    this.setData({
      inputValue: inputValue + emoji,
      showEmojiPanel: false
    });
  }
}); 